package com.gopay.scheduler.job;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.cps.dao.wallet.promotions.WaPromotionsLogDao;
import com.gopay.common.cps.dao.wallet.promotions.WaPromotionsParamDao;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cust.CustPersonInfo;
import com.gopay.common.domain.dps.WaPromotionsLog;
import com.gopay.common.domain.dps.WaPromotionsParam;
import com.gopay.common.domain.wallet.promotions.ActivityBounsResult;
import com.gopay.common.domain.wallet.promotions.ActivityBounsVO;
import com.gopay.common.exception.GopayException;
import com.gopay.common.user.dao.CustPersonInfoQueryDAO;
import com.gopay.remote.cps.wallet.promotions.ActivityBounsService;
import com.gopay.scheduler.GopayBaseJob;
/**
 * 
 * <p>Title: RechargeBounsJob.java</p>
 * <p>Description: 充话费、流量、加油卡送红包活动定时任务</p>
 * <p>Company: 国付宝信息科技有限公司</p> 
 * @author 唐阳
 * @date 2016年1月19日 下午5:07:57
 * @version V1.0
 */
public class RechargeBounsJob extends GopayBaseJob {
	private Logger logger = LoggerFactory.getLogger(RechargeBounsJob.class);
	@Resource(name = "cpsGeneralMainOrderQueryDAO")
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderQueryDAO;
	@Resource(name="waPromotionsLogDAO")
	WaPromotionsLogDao waPromotionsLogDAO;
	@Resource(name="waPromotionsParamDao")
	private WaPromotionsParamDao waPromotionsParamDao;
	@Resource(name="custPersonInfoQueryDao")
	private CustPersonInfoQueryDAO custPersonInfoQueryDao;
	@Resource(name="activitBounsClient")
    private ActivityBounsService activitBounsClient;
	@Override
	protected void doJobInternal() {
		logger.info("------充话费、流量、加油卡送红包活动定时任务开始");
		// TODO Auto-generated method stub
		//获取活动参数：活动开关、付款custid、付款AcctId、付款userId、金额
		 String[] s = {"common_bouns_payCustId",//发红包内部账户的CustId
				 "common_bouns_payAcctId",//发红包内部账户的AcctId
				 "common_bouns_payUserId",//发红包内部账户的UserId
				 "all_recharge_bouns_max_amt",//此次活动的金额上限
				 "tel_recharge_bouns_switch",//充话费送红包活动开关
				 "tel_recharge_bouns_amt",//充话费送红包活动的红包金额
				 "tel_recharge_bouns_start_time",//充话费送红包活动的开始时间
				 "tel_recharge_bouns_end_time",//充话费送红包活动的结束时间
				 "flow_recharge_bouns_switch",//充流量送红包活动开关
				 "flow_recharge_bouns_amt",//充流量送红包活动的红包金额
				 "flow_recharge_bouns_start_time",//充流量送红包活动的开始时间
				 "flow_recharge_bouns_end_time",//充流量送红包活动的结束时间
				 "fuel_recharge_bouns_switch",//充加油卡送红包活动开关
				 "fuel_recharge_bouns_amt",//充加油卡送红包活动的红包金额
				 "fuel_recharge_bouns_start_time",//充加油卡送红包活动的开始时间
				 "fuel_recharge_bouns_end_time",//充加油卡送红包活动的结束时间
				 "tel_recharge_mer_txn_amt",//充话费送红包活动的充值订单金额下限
				 "flow_recharge_mer_txn_amt",//充流量送红包活动的充值订单金额下限
				 "fuel_recharge_mer_txn_amt"};//充加油卡送红包活动的充值订单金额下限
		 //获取活动所需的参数
		 List<WaPromotionsParam> waPromotionsParamList = waPromotionsParamDao.querryByParamKeys(s);
		 Map<String,String> paramMap = new HashMap<String,String>();
		for(WaPromotionsParam param : waPromotionsParamList){
			paramMap.put(param.getParamKey(), param.getParamValue());
		}
		List<String> intTxnCdList = new ArrayList<String>();
		String tel_recharge_bouns_switch = paramMap.get("tel_recharge_bouns_switch");
		String flow_recharge_bouns_switch = paramMap.get("flow_recharge_bouns_switch");
		String fuel_recharge_bouns_switch = paramMap.get("fuel_recharge_bouns_switch");
		if ("1".equals(tel_recharge_bouns_switch)){//充话费送红包开关
			intTxnCdList.add(IntTxnCd._01611.value);
		}
		if ("1".equals(flow_recharge_bouns_switch)){//充流量送红包开关
			intTxnCdList.add(IntTxnCd._01612.value);
		}
		if ("1".equals(fuel_recharge_bouns_switch)){//充加油卡送红包开关
			intTxnCdList.add(IntTxnCd._01613.value);
		}
		if(intTxnCdList.size()>0){
			/* 1、获取参与充值送红包活动的订单
			 * 订单状态为：成功20000
			 * 国付宝内部交易码：01611、01612、01613，根据活动开关开启状态选择
			 * 商户交易金额:根据参数中各活动的订单金额下限
			 * 创建时间：根据参数中各活动的设置的开始时间和结束时间
			 * 2、在活动日志表中不存在的，即未参加过活动的订单
			 */
			List<CpsGenMainOrder> cpsGenMainOrderList = cpsGeneralMainOrderQueryDAO.findByWaPromotionsLog(intTxnCdList,paramMap);
			logger.info("------符合条件的订单数量="+cpsGenMainOrderList.size());
			if(cpsGenMainOrderList.size()>0){
				for(CpsGenMainOrder cpsGenMainOrder : cpsGenMainOrderList){
					giveBouns(cpsGenMainOrder,paramMap);
				}
			}
		}
		logger.info("------充话费、流量、加油卡送红包活动定时任务结束");
	}
	
	/**
	 * 
	 * <p>Description: 统计金额大于符合活动规定金额，在活动期间内发生的充话费、充流量、充加油卡的订单，发红包</p>
	 * @author 唐阳
	 * @date 2016年1月19日 下午5:08:33
	 * @version V1.0 
	 *
	 * @param cpsGenMainOrder
	 * @param paramMap
	 */
	@Transactional
	private void giveBouns(CpsGenMainOrder cpsGenMainOrder ,Map<String,String> paramMap) {
		String gopayIntTxnCd = cpsGenMainOrder.getGopayIntTxnCd();
		logger.info("------交易的gopayOrderId="+cpsGenMainOrder.getGopayOrderId()+",gopayIntTxnCd="+gopayIntTxnCd);
		try{
			String tranAmt = null;
			if(IntTxnCd._01611.value.equals(gopayIntTxnCd)){
				tranAmt = paramMap.get("tel_recharge_bouns_amt");//充话费送红包活动的红包金额
			}else if(IntTxnCd._01612.value.equals(gopayIntTxnCd)){
				tranAmt = paramMap.get("flow_recharge_bouns_amt");//充流量送红包活动的红包金额
			}else if(IntTxnCd._01613.value.equals(gopayIntTxnCd)){
				tranAmt = paramMap.get("fuel_recharge_bouns_amt");//充加油卡送红包活动的红包金额
			}
			//校验总发放金额是否超过6000
			String allAmt = waPromotionsLogDAO.findSumAmtByType();//统计已发放金额汇总
			String maxAmt = paramMap.get("all_recharge_bouns_max_amt");//活动发放金额上限
			if((new BigDecimal(allAmt)).add(new BigDecimal(tranAmt)).compareTo(new BigDecimal(maxAmt))<=0){
				//发付款账户红包
				ActivityBounsVO activityBounsVO = new ActivityBounsVO();
				activityBounsVO.setBounsType("1");
				activityBounsVO.setPayAcctId(paramMap.get("common_bouns_payAcctId"));
				activityBounsVO.setPayCustId(paramMap.get("common_bouns_payCustId"));
				activityBounsVO.setPayUserId(paramMap.get("common_bouns_payUserId"));
				activityBounsVO.setTranAmt(tranAmt);
				activityBounsVO.setRecvAcctId(cpsGenMainOrder.getPayAcct());
				activityBounsVO.setRecvCustId(cpsGenMainOrder.getPayCustId());
				ActivityBounsResult bounsResult = activitBounsClient.activityBouns(activityBounsVO);//调用发红包交易接口
				String gopayOrderId= bounsResult.getGopayOrderId();
				logger.info("------发红包订单gopayOrderId="+gopayOrderId);
				if(gopayOrderId!=null && !"".equals(gopayOrderId)){
					//将参加活动的订单记录到活动日志表
					saveWaPromotionsLog(new BigDecimal(tranAmt),cpsGenMainOrder,gopayOrderId);
				}
			}else{
				logger.error("------充值发红包余额不足,allAmt="+allAmt+",tranAmt="+tranAmt+",maxAmt="+maxAmt);
			}
		}catch(GopayException e){
			logger.error("------充值发红包异常");
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * <p>Description: 记录活动日志</p>
	 * @author 唐阳
	 * @date 2016年1月19日 下午5:10:37
	 * @version V1.0 
	 *
	 * @param amt
	 * @param cpsGenMainOrder
	 * @param gopayOrderId
	 * @return
	 */
	private WaPromotionsLog saveWaPromotionsLog(BigDecimal amt,CpsGenMainOrder cpsGenMainOrder,String gopayOrderId){
		WaPromotionsLog waPromotionsLog = new WaPromotionsLog();
		String gopayIntTxnCd = cpsGenMainOrder.getGopayIntTxnCd();
		String type = null;
		if(IntTxnCd._01611.value.equals(gopayIntTxnCd)){
			type = "4";//充话费发红包
		}else if(IntTxnCd._01612.value.equals(gopayIntTxnCd)){
			type = "5";//充流量发红包
		}else if(IntTxnCd._01613.value.equals(gopayIntTxnCd)){
			type = "6";//充加油卡发红包
		}
		waPromotionsLog.setType(type);//活动类型
		waPromotionsLog.setReward(amt);
		waPromotionsLog.setCondition1(cpsGenMainOrder.getGopayOrderId());//参加抽奖活动的订单号
		waPromotionsLog.setCreateTime(new Date());
		String payCustId = cpsGenMainOrder.getPayCustId();
		waPromotionsLog.setCustId(payCustId);//收红包的custId
		CustPersonInfo custPersonInfo = custPersonInfoQueryDao.getByCustId(payCustId);
		if(custPersonInfo!=null){
			waPromotionsLog.setCustMob(custPersonInfo.getCustMob());
		}
		waPromotionsLog.setCondition2(cpsGenMainOrder.getPayAcct());//收红包的账户
		waPromotionsLog.setGopayOrderId(gopayOrderId);
		logger.info("------记录发红包日志表："+waPromotionsLog.toString());
		return waPromotionsLogDAO.save(waPromotionsLog);
	}
}
